﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SPMS.Log.Repository;

namespace SPMS.Log.Core
{
    /// <summary>
    /// 根日志记录器
    /// </summary>
    /// <remarks></remarks>
    /// <history>
    /// [zanezeng]               2009/10/16 9:43    创建
    /// </history>
    internal sealed class RootLogger : AbstractLogger
    {
        #region ---Constructor

        /// <summary>
        /// 初始化类型<see cref="RootLogger"/>的新实例
        /// </summary>
        /// <param name="repository">根日志记录器关联的日志存储器</param>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2009/10/16 9:45    创建
        /// </history>
        public RootLogger( ILoggingRepository repository )
            : base( LOGGER_NAME, repository.DefaultLevel, repository )
        {
        }

        #endregion

        #region ---Protected Method

        /// <summary>
        /// 添加一条日志记录
        /// </summary>
        /// <param name="entry">要添加的日志记录条目</param>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2009/10/9 9:23    创建
        /// </history>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2009/10/16 9:44    创建
        /// </history>
        protected override void AppendEntry( LogEntry entry )
        {
            //获得关联到日志记录器上的日志追加器
            ILogAppender[] appenders = this.Repository.Appenders;

            //判断是否设置了日志追加器
            if (null == appenders || 0 == appenders.Length)
            {
                //输出日志
                if (LoggingContext.MetaLog.IsWarnEnabled)
                {
                    LoggingContext.MetaLog.Warn( "日志对象'{0}'上没有附加任何日志记录器，无法输出日志条目'{1}'", this.Name, entry );
                }

                //直接返回
                return;
            }

            //循环往所有的日志记录器中输出日志
            foreach (ILogAppender appender in appenders)
            {
                try
                {
                    //将日志条目写入日志记录器
                    appender.Append( entry );
                }
                catch (Exception exception)
                {
                    //输出日志
                    if (LoggingContext.MetaLog.IsErrorEnabled)
                    {
                        LoggingContext.MetaLog.Error( exception, "将日志条目'{0}'写入日志'{1}'关联的日志追加器'{2}'失败", entry, this.Name, appender.Name );
                    }
                }
            }
        }

        #endregion

        #region ---Field

        /// <summary>
        /// 日志记录器的名称
        /// </summary>
        private const string LOGGER_NAME = "root";

        #endregion
    }
}
